# -*- coding: utf-8 -*-
"""
Created on Wed May 28 15:08:41 2025

@author: wangwenjie
"""

import os
import rqdatac
import pandas as pd
import numpy as np
import datetime
from datetime import date
start_date='2025-01-01'
end_date = date.today() - datetime.timedelta(days=1)
end_date = end_date.strftime('%Y-%m-%d')
rqdatac.init('license', 'AcBHy5_JJ6wjZdu7Q-ey7dX-J3BmyEC_KblY2Q_hBeOuoBaeBbgXTNSe6XZvqKVESbyUf7vMpLLGuO_aqyb3w9fWGI7q4wdClE6cMp_Z3N4PqqTHJ0nr3CIuXtk-5XzSD1p7NTdNcrAfZlRVpMMtY_PDC9FYuXNmC_EnuQg4H-A=fGk9EhHcK3xN189iXYSWLyiMdGUeXXlVZqr2MxhBypSHxQYnIIyxyM8BR8oNnVUdWhKx-ZrFRIjSONd7uYpOvpcBab92P60iAR_JopX61emtrvsY1xG_uCfYhDPBdDSJKaniJhTPuoBIU4JZun8-8fMIxzx7lnwBm2kAUOA_Mpg=')
print('instrument')
instrument = rqdatac.all_instruments(type='Convertible', market='cn', date=None)
bond_code = instrument['order_book_id'].unique()
industry = rqdatac.convertible.get_instrument_industry(bond_code)

balance = rqdatac.convertible.get_indicators(bond_code, start_date=start_date, end_date=end_date, fields='remaining_size').reset_index()
balance = balance.drop_duplicates(subset=['order_book_id','date'])
balance = balance.set_index(['order_book_id','date'])


def shift(df_slice):
    df = df_slice.sort_values(by='date', ascending=True)
    df = df.set_index(['date'])
    df = df.shift(-1)
    return df

iv = rqdatac.convertible.get_indicators(bond_code,start_date=start_date, end_date=end_date, fields='iv')
iv = iv.reset_index()
iv = iv.groupby('order_book_id').apply(shift)
price = rqdatac.get_price(bond_code,start_date=start_date, end_date=end_date, frequency='1d',fields='close')
price = price.reset_index()
price = price.groupby('order_book_id').apply(shift)
pct = rqdatac.get_price_change_rate(bond_code, start_date=start_date, end_date=end_date, expect_df=True)
pct = pd.DataFrame(pct.stack()).reset_index()
pct = pct.set_index(['order_book_id','date'])

data = price.copy()
data.columns = ['code','close']
data['balance'] = balance
data['iv'] = iv['iv']
data['pct'] = pct
data = data.merge(industry['first_industry_name'], left_on='code', right_index=True, how='left')

#data = data.dropna(how='any')
data = data[['close','iv','pct','first_industry_name','balance']]
data1 = data.reset_index()

# 模拟低隐波策略
def cal(df_slice):
    df = df_slice.sort_values(by='iv', ascending=True)
    df = df.iloc[:120,:]
    #df = df_slice[df_slice.close >= 130]
    return df
    
result = data1.groupby('date').apply(cal)
result1 = result['pct'].reset_index()
result1 = result1.groupby('date').mean()
result1 = pd.DataFrame(result1['pct'])

result1 = result1[result1.index >= '2018-12-28 00:00:00']
result1.iloc[0,:] = 0
df = (1+result1).cumprod()

# 分行业行情
result2 = data1.groupby(['date','first_industry_name'])['pct'].mean()
result2 = result2.reset_index()
result2 = result2.pivot('date','first_industry_name','pct')
result2 = result2[result2.index >= '2025-04-18 00:00:00']
result2.iloc[0,:] = 0
df_industry = (1+result2).cumprod()

# 分股债性行情
data2 = data1.copy()
data2['price_level'] = np.nan
data2.loc[data2.close >= 130,'price_level'] = '130以上'
data2.loc[(data2.close >= 120) & (data2.close < 130),'price_level'] = '120-130'
data2.loc[(data2.close >= 110) & (data2.close < 120),'price_level'] = '110-120'
data2.loc[data2.close < 110,'price_level'] = '110以下'

result3 = data2.groupby(['date','price_level'])['pct'].mean()
result3 = result3.reset_index()
result3 = result3.pivot('date','price_level','pct')
result3 = result3[result3.index >= '2025-04-18 00:00:00']
result3.iloc[0,:] = 0
df_price = (1+result3).cumprod()


# 股债性占比
result4 = data2.groupby(['date','price_level'])['balance'].sum().reset_index()
result4 = result4.pivot('date','price_level','balance')/100000000
result5 = result4.copy()
for i in result5.columns:
    result5.loc[:,i] = result4.loc[:,i] / result4.sum(1)
result5 = result5[result5.index >= '2025-01-01 00:00:00']

# 价格中枢
def cal_price(df_slice):
    df = df_slice[['date','order_book_id','close','balance']]
    df['weight'] = df['balance'] / df['balance'].sum() 
    df_price = (df['weight']*df['close']).sum()
    return df_price
result6 = data2.groupby('date').apply(cal_price)


